package com.cloud.cmt.cmtcontrol.clusterdatasource;

import com.alibaba.druid.util.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * User: wcy
 * Date: 2017/9/12
 * Time: 17:35
 */
@Aspect
@Order(-1) // 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

    private final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);

    @Before("execution(* com.cloud.cmt.cmtcontrol.dao.*.*(..))")
    public void before(JoinPoint point) {

        Object target = point.getTarget();
        Class<?>[] classz = target.getClass().getInterfaces();

        if (classz[0].isAnnotationPresent(TargetDataSource.class)) {
            TargetDataSource data = classz[0].getAnnotation(TargetDataSource.class);
            if(!StringUtils.isEmpty(data.value())){
                DynamicDataSourceContextHolder.setDataSourceType(data.value());
            }else
                DynamicDataSourceContextHolder.setDataSourceType(DynamicThreadLocal.getTenlentId());
            logger.info("DataSource：" + DynamicThreadLocal.getTenlentId());
        }
    }

    @After("execution(* com.cloud.cmt.cmtcontrol.dao.*.*(..))")
    public void restoreDataSource(JoinPoint point) {
        DynamicDataSourceContextHolder.clearDataSourceType();
    }
}

